from django.shortcuts import render, redirect

# Create your views here.


def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == "root" and pwd == "123":
            # 生成随机字符串
            # 写到用户浏览器cookie
            # 保存到session中
            # 在随机字符串对应的字典中设置相关内容
            request.session['user'] = user
            request.session['is_login'] = True
            return redirect('/index/')
        else:
            return render(request, 'login.html')


def auth(func):
    def wrap(request, *args, **kwargs):
        if request.session.get('is_login', False) is not True:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return wrap


@auth
def index(request):
        user = request.session['user']
        return render(request, 'index.html', {'user': user})


def loginout(request):
    request.session.clear()
    return redirect('/login/')


########################from###########################
from django import forms
from django.forms import widgets
from django.forms import fields


class FM(forms.Form):
    user = fields.CharField(
        error_messages={'required': '*用户名不能为空.'},
        label="用户名",
        widget=widgets.Textarea(attrs={'class': 'c1', 'name': 'userneme'})  # 调用样式和添加插件
    )
    pwd = fields.CharField(
        max_length=12,
        min_length=6,
        error_messages={
            'required': '*密码不能为空.', 'min_length': '*密码长度不能小于6', "max_length": '*密码长度不能大于12'
        },
        widget=widgets.PasswordInput(attrs={'class': 'c2'})
    )
    email = fields.EmailField(error_messages={'required': '*邮箱不能为空.', 'invalid': "*邮箱格式错误"})
    f = fields.FileField()

    # p = fields.FilePathField(path='app01')
    city1 = fields.ChoiceField(
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )
    city2 = fields.MultipleChoiceField(
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )

    uc = fields.MultipleChoiceField(
        initial=[2, ],
        choices=((1, '上海'), (2, '北京'),),
        widget=widgets.CheckboxSelectMultiple
    )

def fm(request):
    if request.method == "GET":
        obj = FM()
        return render(request, 'fm.html', {'obj': obj})
    elif request.method == "POST":
        obj = FM(request.POST)
        r1 = obj.is_valid()
        if r1:
            print(obj.cleaned_data)
            # module.UserInfo.objects.create(**obj.cleaned_data) # 写入数据库
            return render(request, 'fm.html')
        else:
            print(obj.errors)
            return render(request, 'fm.html', {'obj': obj})

